package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
	"time"
)

type DeepseekClient struct {
}

func NewDeepseekClient() *DeepseekClient {
	return &DeepseekClient{}
}

/*
*

	func (r *DeepseekClient) Chat(inputMessage string) {
		// create deepseek api client
		ai_config := AIConfig{}
		DB.Model(&AIConfig{}).First(&ai_config)

		if ai_config.ApiKey == "" {
			panic("no api key")
		}
		cli, _ := deepseek.NewClient(ai_config.ApiKey)

		chatReq := &request.ChatCompletionsRequest{
			Model:  deepseek.DEEPSEEK_REASONER_MODEL,
			Stream: true,
			Messages: []*request.Message{
				{
					Role:    "user",
					Content: inputMessage,
				},
			},
		}
		fmt.Printf("input message => %s\n", chatReq.Messages[0].Content)

		// call deepseek api
		sr, err := cli.StreamChatCompletionsReasoner(context.Background(), chatReq)
		if err != nil {
			fmt.Println("error => ", err)
			return
		}

		fmt.Print("output message => ")
		for {
			chatResp, err_ := sr.Read()
			if err_ != nil {
				if err_ == io.EOF {
					break
				}
				MessageChan <- err_.Error()
				return
			}
			if chatResp.Choices[0].Delta.ReasoningContent != "" {
				MessageChan <- chatResp.Choices[0].Delta.ReasoningContent
			} else {
				MessageChan <- chatResp.Choices[0].Delta.Content
			}
		}
	}
*/
type Logprobs struct {
	TextOffset    []int                `json:"text_offset"`
	TokenLogprobs []float64            `json:"token_logprobs"`
	Tokens        []string             `json:"tokens"`
	TopLogprobs   []map[string]float64 `json:"top_logprobs"`
}

type Choice struct {
	Index              int      `json:"index"`
	Delta              string   `json:"delta"`
	Content            string   `json:"content"`
	Reasoning          *string  `json:"reasoning"`
	FinishReason       *string  `json:"finish_reason"`
	NativeFinishReason *string  `json:"native_finish_reason"`
	Logprobs           Logprobs `json:"logprobs"`
}

type DeltaStruct struct {
	Role      string  `json:"role"`
	Content   string  `json:"content"`
	Reasoning *string `json:"reasoning"`
}

type ChoiceWithDeltaStruct struct {
	Index              int         `json:"index"`
	Delta              DeltaStruct `json:"delta"`
	FinishReason       *string     `json:"finish_reason"`
	NativeFinishReason *string     `json:"native_finish_reason"`
	Logpro             Logprobs    `json:"logpro"`
}

type Response struct {
	ID       string   `json:"id"`
	Provider string   `json:"provider"`
	Model    string   `json:"model"`
	Object   string   `json:"object"`
	Created  int64    `json:"created"`
	Choices  []Choice `json:"choices"`
}

type ResponseWithDeltaStruct struct {
	ID       string                  `json:"id"`
	Provider string                  `json:"provider"`
	Model    string                  `json:"model"`
	Object   string                  `json:"object"`
	Created  int64                   `json:"created"`
	Choices  []ChoiceWithDeltaStruct `json:"choices"`
}

func (r *DeepseekClient) FreeChat(inputMessage string) error {
	var api_key = "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"
	// 定义 API 地址
	url := "https://openrouter.ai/api/v1/chat/completions"

	// 定义请求体
	requestBody := map[string]interface{}{
		"model": "deepseek/deepseek-r1-distill-qwen-32b:free",
		"messages": []map[string]string{
			{
				"role":    "user",
				"content": inputMessage,
			},
		},
		"stream": true,
		"chain":  true,
	}

	// 将请求体转换为 JSON
	jsonBody, err := json.Marshal(requestBody)
	if err != nil {
		return fmt.Errorf("JSON 编码失败: %v", err)
	}

	// 创建 POST 请求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBody))
	if err != nil {
		return fmt.Errorf("创建请求失败: %v", err)
	}

	// 设置 Header 参数
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", api_key))
	req.Header.Set("Content-Type", "application/json")

	// 创建 HTTP 客户端
	client := &http.Client{
		Timeout: 30 * time.Second, // 设置超时时间
	}

	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return fmt.Errorf("请求失败: %v", err)
	}
	defer resp.Body.Close() // 确保关闭响应体

	// 使用 bufio.Scanner 逐行读取流式响应
	scanner := bufio.NewScanner(resp.Body)
	for scanner.Scan() {
		line := scanner.Bytes() // 获取当前行的字节数据
		if strings.Contains(string(line), "OPENROUTER PROCESSING") {
			continue
		}
		if bytes.HasPrefix(line, []byte("data: ")) {
			line = line[6:] // 去除 "data: " 前缀
			if string(line) == "[DONE]" {
				break
			}

		}
		if len(line) == 0 {
			continue // 跳过空行
		}
		// 解析 JSON 数据
		chunk := ResponseWithDeltaStruct{}
		if err := json.Unmarshal(line, &chunk); err != nil {
			fmt.Printf("解析 JSON 失败: %v, 原始数据: %s\n", err, line)
			continue
		}

		FreeChan <- chunk
	}

	// 检查扫描错误
	if err := scanner.Err(); err != nil {
		return fmt.Errorf("读取流式响应失败: %v", err)
	}

	return nil
}
